const r = require("../../libs/cos-auth");
import Dialog from "@vant/weapp/dialog/dialog";

const app = getApp();
const {reportMixin} = app._require("pages/declare-view/sb-action.js");
const {
    AskPage
} = app._require("common/index");
const formMixin = app._require("mixins/form.mixin.js").default;
AskPage({
    name: "declre-view",
    mixins: [formMixin, reportMixin],
    data: {
        url: "https://img.yzcdn.cn/vant/cat.jpeg",
        navBarHeight: app.globalData.navBarHeight,//导航栏高度
        item: {},
        formId: "",
        formName: "",
        departmentName: "",
        createTime: "",
        deadTime: "",
        state: 2,
        approvalStatus: '',
        category: '',
        id: "",
        processInstanceId: '',
        total: '',
        tips: "请确认已采集完成所有数据,提交后将结束本任务,并无法再次进行填报。",
        currentPage: 1,
        showContent: false,
        showOnFillPop: false,
        isCompleteApproval: false,
        selectItems: {},
        searchValue: '',
        submit: {
            show: false
        },
        assign: {
            show: false,
            active: -1,
        },
        actions: [],
        share: {
            show: false,
            item: null,
            list: [
                {name: "转发给其他人填报", value: "orgOut", openType: "share", taskId: ""},],
        },
        collectionData: [],
        records: [],
        steps: [],
        reviewData: [
            {}
        ],
        triggered: false
    },
    onClose() {
        this.setData({'assign.show': false});
    },
    onSelect(event) {
        Dialog.confirm({
            title: "提示",
            message: `您确认要把该任务指派给${event.detail.name}吗？`
        })
            .then(async () => {
                Dialog.confirm({
                    title: "提示",
                    message: `本任务指派给他人后，您是否仍然保留对当前任务的填报和提交等操作功能。`,
                    showConfirmButton: true,
                    showCancelButton: true,
                    confirmButtonText: '不保留',
                    confirmButtonColor: '#02bb00',
                    cancelButtonText: '保留'
                })
                    .then(async () => {
                        const res = await this.$_server("task/turnTask", {
                            data: {
                                taskId: this.data.id,
                                userId: event.detail.id,
                            },
                        });
                        if (res.data.code === 200) {
                            setTimeout(() => {
                                wx.showToast({
                                    title: `已指派给${event.detail.name}`,
                                    icon: "success",
                                    duration: 2000,
                                    success: () => {
                                        const pages = getCurrentPages();
                                        const beforePage = pages[pages.length - 2];
                                        beforePage.initData();
                                        wx.navigateBack({
                                            delta: 1, // 返回上一级页面。
                                        });
                                    },
                                });
                            });
                        } else {
                            setTimeout(() => {
                                wx.showToast({
                                    title: res.data.message,
                                    icon: "error",
                                    duration: 2000,
                                });
                            });
                        }
                    })
                    .catch(async (e) => {
                        console.log(e);
                        const res = await this.$_server("task/addProcess", {
                            data: {
                                processInstId: this.data.processInstanceId,
                                users: [event.detail.id]
                            },
                        });
                        if (res.data.code === 200) {
                            setTimeout(() => {
                                wx.showToast({
                                    title: `已指派给${event.detail.name}`,
                                    icon: "success",
                                    duration: 2000,
                                    success: () => {
                                        const pages = getCurrentPages();
                                        const beforePage = pages[pages.length - 2];
                                        beforePage.initData();
                                        wx.navigateBack({
                                            delta: 1, // 返回上一级页面。
                                        });
                                    },
                                });
                            });
                        } else {
                            setTimeout(() => {
                                wx.showToast({
                                    title: res.data.message,
                                    icon: "error",
                                    duration: 2000,
                                });
                            });
                        }
                    });
            })
            .catch(() => {
            });
    },
    onLoad(options) {
        console.log(options, 'optionsoptionsoptionsoptions')
        var item = JSON.parse(options.item);
        console.log(item, 'item');
        this.setData({
            "item": item,
            "formName": options.formName || "",
            "departmentName": options.departmentName || "",
            "createTime": options.createTime || "",
            "deadTime": options.deadTime || "",
            "formId": options.formId || "",
            "id": options.id,
            state: options.state,
            approvalStatus: options.approvalStatus,
            category: options.category,
            processInstanceId: options.processInstanceId,
            user: app.user,
            isCopy: options.isCopy || '',
            childTask: options.childTask || '',
            triggered: true
        });
        let type = item.source.type;
        if (type != "report") {
            if (options.isCopy !== "isCopy") {
                this.initShowNode();
            }
            this.getFormWxacode(item.source);
        } else {
            this.getDeclareDetails();
        }
    },
    onShow(options) {
        this.getPerson();
        let type = this.data.item.source.type;
        if (type != "report") {
            if (this.data.clickInBigImage != true) {
                this.onList();
            }
            this.setData({
                "clickInBigImage": false
            })
        } else {
        }
    },
    scrollReachBottom() {
        this.setData({
            currentPage: this.data.currentPage + 1
        })
        setTimeout(() => {
            this.onList(this.data.currentPage);
        })
    },
    onRefresh() {
        if (this._freshing) return
        this._freshing = true
        setTimeout(() => {
            this.onList();
            this.setData({
                triggered: false
            })
            this._freshing = false
        }, 500)
    },
    //获取小程序二维码
    async getFormWxacode(source) {
        console.log(source);
        let formId = source.formId;
        let processInstanceId = source.processInstanceId;
        const response = await this.$_server("task/getFormWxacode", {
            params: {
                formId: "?formId=" + formId + "&processInstId=" + processInstanceId,
            },
        });
        let {data} = response;
        if (data.code == 200) {
            let imgData = data.data || "";

            this.setData({
                "codeData": "data:image/png;base64," + imgData,
                "showCode": imgData.length > 0 ? true : false
            })
        }
    },
    clickDownload(e) {
        if (!this.data.showCode) {
            console.log("为获取到二维码");
            return;
        }
        var imgSrc = this.data.codeData;//base64编码
        var save = wx.getFileSystemManager();
        var number = Math.random();
        save.writeFile({
            filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
            data: imgSrc.slice(22),
            encoding: 'base64',
            success: res => {
                wx.saveImageToPhotosAlbum({
                    filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
                    success: function (res) {
                        wx.showToast({
                            title: '保存成功',
                        })
                    },
                    fail: function (err) {
                        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail:auth denied") {
                            console.log("当初用户拒绝，再次发起授权")
                            wx.showModal({
                                title: '提示',
                                content: '需要您授权保存相册',
                                showCancel: false,
                                success: () => {
                                    wx.openSetting({
                                        success(settingdata) {
                                            console.log("settingdata", settingdata)
                                            if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: '获取权限成功,再次点击图片即可保存',
                                                    showCancel: false,
                                                })
                                            } else {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: '获取权限失败，将无法保存到相册哦~',
                                                    showCancel: false,
                                                })
                                            }
                                        },
                                        fail(failData) {
                                            console.log("failData", failData)
                                        },
                                        complete(finishData) {
                                            console.log("finishData", finishData)
                                        }
                                    })
                                }
                            })
                        }
                    }
                })
            }, fail: err => {
            }
        })
    },
    async onList(page = 1) {
        const userInfo = (app.user && app.user.userInfo) || {};
        try {
            let url = "";
            if (this.data.isCopy === "isCopy") {
                url = "task/all/flowData"
            } else if (this.data.approvalStatus == 'null' && this.data.state != '2') {
                if (this.data.approvalStatus!=null && this.data.category!='approval') {
                    url = "form/taskDataList";
                } else if (this.data.approvalStatus == 'null' && this.data.category =='approval') {
                    url = "form/processTaskDataList";
                } else if (app.user.userInfo.orgCategoryId == "9") {
                    url = "form/taskDataList";
                } else {
                    url = "form/processTaskDataList";
                }
            } else {
                url = "form/processTaskDataList";
            }
            const serviceData = this.data.isCopy === "isCopy" ? {
                formId: this.data.formId || "",
                processInstIds: this.data.childTask.split(","),
                firstItemValue: this.data.searchValue,
                currentPage: page,
                pageSize: 20,
            } : {
                type: 1,
                formId: this.data.formId || "",
                collectorId: url === "form/taskDataList" ? userInfo.id || "" : undefined,
                processInstId: this.data.processInstanceId || "",
                firstItemValue: this.data.searchValue,
                currentPage: page,
                pageSize: 20,
            }
            const response = await this.$_server(url, {
                data: serviceData,
            });
            let {data} = response;
            if (data.code !== 200) {
                throw data;
            }
            this.setData({
                currentPage: page,
            });
            wx.stopPullDownRefresh({
                success: (res) => {
                },
            })
            let records = data.data.records;
            if (page == 1) {
            } else {
                let new_records = this.data.records ?? [];
                records = new_records.concat(records)
            }
            let collectionData = [];
            for (const key in records) {
                const element = records[key];
                collectionData.push({
                    title: element.name,
                    date: element.createTime,
                    formId: element.formId,
                    dataFormId: element.dataFormId,
                    collector: element.collector,
                    collectorId: element.collectorId,
                    firstItemValue: element.firstItemValue || "",
                    verify: element.verify,
                    reason: element.verifyCause
                })
            }
            this.setData({
                records: records,
                isFinlishLoad: records.length === data.data.total,
                total: data.data.total,
                collectionData: collectionData
            })
            if (page > 1) {
                wx.stopPullDownRefresh();
            }
        } catch (error) {
            if (error.message) {
                wx.showToast({
                    mask: true,
                    title: error.message,
                    icon: "none",
                    duration: 2000,
                });
            } else {
                throw error;
            }
        }
    },
    assign() {
        if (this.data.actions.length) {
            this.setData({
                "assign.show": true,
            });
        } else {
            wx.showToast({
                title: "暂无指派人员",
                icon: 'success',
                duration: 2000
            })
        }
    },
    async getPerson() {
        const userInfo = (app.user && app.user.userInfo) || {};
        const res = await this.$_server('task/person', {
            params: {
                governmentId: "?governmentId=" + userInfo.governmentId
            },
        })
        if (res.data.code === 200) {
            const list = res.data.data.filter((item) => {
                return item.id !== userInfo.id && item.orgCategoryId === userInfo.orgCategoryId
            })
            this.setData({
                actions: list
            })
        }
    },
    onShare() {
        let item = this.data.item;
        let auth = this.checkAuth();
        if (!auth) return;
        this.data.share.item = item;
        this.setData({
            "share.show": true,
        });
        this.onShareAppMessage();
    },
    onShareAppMessage: function (e) {//点击button分享按钮触发此分享事件
        const userInfo = (app.user && app.user.userInfo) || {};
        return {
            title: '表单填报：' + this.data.formName,
            path: "/pages/home/collection/collection-details/index?formId=" +
                this.data.formId +
                "&dataCount=" + this.data.total +
                "&type=share" +
                "&userId=" + userInfo.id +
                "&processInstanceId=" + this.data.processInstanceId +
                "&taskId=" + this.data.id +
                "&cityCode=" + userInfo.cityCode +
                "&governmentId=" + userInfo.governmentId +
                "&orgCategoryId=" + userInfo.orgCategoryId +
                "&departmentId=" + userInfo.departmentId,
            success: function (res) {
                // 转发成功
                wx.showToast({
                    title: "分享成功",
                    icon: 'success',
                    duration: 2000
                })
            },
            fail: function (res) {
                // 分享失败
                wx.showToast({
                    title: "分享失败",
                    icon: 'success',
                    duration: 2000
                })
            },
        }
    },
    onShareClose() {
        this.setData({
            "share.show": false,
        });
    },
    submit() {
        this.setData({
            "submit.show": true,
        });
    },
    onSubmit() {
        this.onEnd();
        this.setData({
            "submit.show": false,
        });
    },
    showAllContent() {
        this.setData({
            "showContent": !this.data.showContent
        })
    },
    onFillAction() {
        wx.showModal({
            title: "",
            content: "确认提交?",
            success: (res) => {
                if (res.confirm) {
                    this.onEnd();
                    //    console.log("确定");
                } else if (res.cancel) {
                    console.log("用户点击取消");
                }
            },
        });
    },
    async onEnd() {
        let auth = this.checkAuth();
        if (!auth) return;
        let info = {
            msg: "任务已完成",
            errMsg: "状态修改失败"
        }
        try {
            const response = await this.$_server("task/finish", {
                data: {
                    taskId: this.data.id
                },
            });
            let {data} = response;
            if (data.code !== 200) {
                throw data;
            }
            wx.askShowToastEx({
                mask: true,
                title: info.msg || "状态已更新",
                icon: "none",
                duration: 2000,
                cancel: () => {
                    const _page = this.getPage();
                    if (_page) {
                        _page.loginSuccess();
                    }
                },
            });
            this.setData({
                state: 2
            })
            let eventChannel = this.getOpenerEventChannel();
            try {
                eventChannel.emit('updateDataAction',);
            } catch (e) {
            }
        } catch (error) {
            console.log(error);
            // statements
            if (error.message) {
                wx.showToast({
                    mask: true,
                    title: error.message || info.errMsg,
                    icon: "none",
                    duration: 2000,
                });
            } else {
                throw error;
            }
        }
    },
    onFillin() {
        const userInfo = (app.user && app.user.userInfo) || {};
        wx.navigateTo({
            url: "/pages/home/collection/collection-details/index?formId=" + this.data.formId + "&dataCount=" + this.data.collectionData.length + "&processInstanceId=" + this.data.processInstanceId + "&userId=" + userInfo.id + "&goBackLast=true" + "&type=sb_report"
        });
    },
    Fillin() {
        const userInfo = (app.user && app.user.userInfo) || {};
        wx.navigateTo({
            url: "/pages/home/collection/collection-details/index?formId=" + this.data.formId + "&dataCount=" + this.data.collectionData.length + "&processInstanceId=" + this.data.processInstanceId + "&userId=" + userInfo.id + "&goBackLast=true"
        });
    },
    approvalAction(e) {
        this.setData({
            "showOnFillPop": !this.data.showOnFillPop,

        })
    },
    details(e) {
        var idx = e.currentTarget.dataset.index;
        var list = this.data.collectionData;
        console.log(idx, list);
        const userInfo = (app.user && app.user.userInfo) || {};
        wx.navigateTo({
            url:
                "/pages/home/collection/collection-details/index?formId=" +
                list[idx].formId +
                "&id=" +
                list[idx].dataFormId +
                "&state=" +
                this.data.state +
                "&dataCount=" +
                this.data.collectionData.length +
                "&userId=" +
                userInfo.id +
                "&approvalStatus=" +
                this.data.approvalStatus +
                "&category=" +
                this.data.category +
                "&clickNext=" +
                true +
                "&verify=" +
                list[idx].verify +
                "&reason=" +
                list[idx].reason +
                "&isCopy=" +
                this.data.isCopy,
        });
    },
    deleteAction(e) {
        let index = e.currentTarget.dataset.index;
        let item = e.currentTarget.dataset.item;
        wx.showModal({
            title: "",
            content: "是否确认删除?",
            success: (res) => {
                if (res.confirm) {
                    this.deteleDataAction(item, index)
                } else if (res.cancel) {
                }
            },
        })
    },
    async deteleDataAction(item, index) {
        let dataFormId = item.dataFormId || "";
        let response = await this.$_server(
            "form/reportDelete", {
                data: {
                    dataFormId: dataFormId,//url.fileName,
                },
            }
        );
        let {data} = response;
        wx.askShowToastEx({
            title: data.message,
            icon: "none"
        })
        if (data.code == 200) {
            var collectionData = this.data.collectionData;
            collectionData.splice(index, 1)
            this.setData({
                collectionData: collectionData,
                total: this.data.total - 1
            })
        }
    },
    clickChoseItem(e) {
        let index = e.currentTarget.dataset.index;
        let item = e.currentTarget.dataset.item;
        let selectItems = this.data.selectItems;
        if (selectItems[index]) {
            delete selectItems[index]
        } else {
            selectItems[index] = item
        }
        let nameItems = ""
        for (let key in selectItems) {
            let value = selectItems[key]
            let name = (parseInt(key) + 1) + "." + value.firstItemValue;
            if (nameItems.length == 0) {
                nameItems = name;
            } else {
                nameItems = nameItems + "," + name;
            }
        }
        this.setData({
            "selectItems": selectItems,
            "nameItems": nameItems
        })
    },
    actionEnd(e) {
        let approvedStatus = e.detail.approvedStatus;
        this.onPullDownRefresh();
        this.setData({
            "nameItems": "",
            "selectItems": {},
            "approvalStatus": approvedStatus,
        })
        let eventChannel = this.getOpenerEventChannel();
        try {
            eventChannel.emit('updateDataAction',);
        } catch (e) {
        }
    },
    //点击了图片
    imageClickDownload(e) {
        let item = e.currentTarget.dataset.codedata;
        wx.previewImage({
            urls: [item], //需要预览的图片http链接列表，注意是数组
            current: "", // 当前显示图片的http链接，默认是第一个
            success: function (res) {
            },
            fail: function (res) {
                console.log(res);
            },
            complete: function (res) {
            },
        });
        this.setData({
            "clickInBigImage": true
        })
    },
    reloadToatal() {
        try {
            let pagetotal = getCurrentPages() //所有的路径 数组
            let parpage = pagetotal[pagetotal.length - 3] //父级页面
            if (parpage.name == 'home') {
                parpage.reloadToatalAction();
            }
        } catch (e) {
            console.log(e);
        }
    },
    clickErrorItem(e) {
        let reason = e.currentTarget.dataset.reason;
        if (reason.length > 0) {
            wx.showToast({
                title: reason,
                duration: 2000,
                icon: "none"
            })
        }
    },
    onInput(e) {
        this.setData({
            searchValue: e.detail.value
        });
    },
    searchList() {
        this.onList();
    },
    searchAllList() {
        this.setData({
            searchValue: ""
        });
        this.onList();
    }
})
